<template>
  <div id="complaint-advice-list" class="app-container">
    <list-search-bar
      ref="searchbar"
      :showAdd="false"
      :search-rule="searchRule"
      @submit="getList($event, pageInfo)"
      @add="showEdit()"
      @update:value="searchData = $event"
    />
    <list-table
      :showEdit="false"
      :showRemove="false"
      @edit="showEdit($event)"
      @remove="remove"
      v-loading="listLoading"
      :listRule="editRule"
      :listData="listData"
      :tableHeight="tableHeight - 30"
    >
      <template slot="btn-group" slot-scope="{ row }">
        <el-button size="mini" @click="lookEdit(row)">查看</el-button>
      </template>
    </list-table>
    <pagination
      :page-sizes="[20]"
      :page-size="pageInfo.size"
      :current-page="pageInfo.page"
      :total="pageInfo.total"
      @pagination="getList(searchData, { ...pageInfo, page: $event.page })"
    />
    <back-to-top
      :visibility-height="300"
      :back-position="0"
      transition-name="fade"
    />
    <el-dialog
      :close-on-click-modal="false"
      width="50%"
      :visible.sync="lookDialog"
      v-loading="editLoading"
      title="详情"
      v-dialogDrag
      custom-class="widget-dialog widget-form widget-search center no-margin color-white black-bg2"
    >
      <form-create
        v-model="editFormInstance"
        :value.sync="lookData"
        :rule="lookRules"
        :option="editOptions"
      />
      <flow-from :workAll="workAll" :orderType="1"></flow-from>

      <template slot="footer">
        <el-button size="mini" @click="lookDialog = false">关闭</el-button>
      </template>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      width="500px"
      :visible.sync="editDialog"
      v-loading="editLoading"
      title="填写信息"
      v-dialogDrag
      custom-class="widget-dialog widget-form widget-search center no-margin color-white black-bg2"
    >
      <form-create
        v-model="editFormInstance"
        :value.sync="editData"
        :rule="editRule"
        :option="editOptions"
      />
      <template slot="footer">
        <el-button size="mini" @click="reset">重置</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  tsjyTsjyDetailNew,
  tsjyGetList as searchApi, //获取列表的api
  tsjyAdd as updateApi, //更新、新增数据的api
  tsjyEdit as chuliApi, //处理
  mock as removeApi //删除数据的api
} from "@/api";
import {
  editRule,
  searchRule,
  chuliRule
} from "@/formRules/system/ComplaintAdviceListRules";
import { editFormOptions, getData } from "@/formRules";
import checkPermission from "@/utils/permission";
import { isDev } from "@/configurations.js";
import mixin from "@/mixins/tableAutoHeight";
import { mapState } from "vuex";
export default {
  name: "ComplaintAdviceList",
  configurations: {
    title: "留言列表",
    isDefault: true,
    show: true
  },
  mixins: [mixin],
  data() {
    return {
      editRule: editRule(),
      lookRules: editRule(),
      chuliRule: chuliRule(),
      listData: [],
      searchRule: searchRule(),
      searchData: {
        type: "",
        userName: ""
      }, //搜索表单数据
      editFormInstance: {},
      editData: {},
      lookData: {},
      editOptions: editFormOptions(),
      editDialog: false,
      lookDialog: false,
      editLoading: false,
      listLoading: false,
      isDual: false,
      pageInfo: {
        page: 1,
        size: 20,
        total: 0
      },
      workList: [],
      permissionList: [] //权限列表
    };
  },
  // 在路由导航进来之前检查权限
  beforeRouteEnter(from, to, next) {
    const permissionList = checkPermission(to.path);
    if (permissionList.length) {
      next(vm => {
        vm.permissionList = permissionList;
      });
      return;
    }
    next({
      name: "403"
    });
  },
  mounted() {
    this.lookRules.forEach(e => {
      e.props = {
        disabled: true
      };
    });

    this.$nextTick(() => {
      this.initSearch();
      setTimeout(() => {
        this.getList(this.searchData, this.pageInfo);
      }, 0);
    });
  },
  watch: {
    "searchData.companyTreeId"(n, old) {
      if (n == old) {
        return;
      }
      if (n.length) {
        this.$refs.searchbar.formInstance.updateRule("companyId", {
          options: this.userCompanyList.filter(
            e => Number(e.parentCompanyId) == n
          ),
          value: ""
        });
      } else {
        this.$refs.searchbar.formInstance.updateRule("companyId", {
          options: this.userCompanyList,
          value: ""
        });
      }
    }
  },
  computed: {
    workAll() {
      if (!this.workList.length) return [];
      return this.workList.sort(function(a, b) {
        let aTime = new Date(a.createTime),
          bTme = new Date(b.createTime);
        return aTime - bTme;
      });
    },
    ...mapState(["user", "userCompanyList"]),
    userName() {
      return this.user?.username;
    },
    queryName() {
      return this.$route?.query?.userName || "";
    },
    // 根据获取的权限列表此处返回各个权限的显示与否
    permissions() {
      return ["edit", "remove", "add"].reduce((pre, cur) => {
        pre[cur] = isDev ? true : this.permissionList.includes(cur);
        return pre;
      }, {});
    }
  },
  methods: {
    initSearch() {
      if (this.$route?.query?.type) {
        this.searchData.type = this.$route?.query?.type;
      }
    },
    /**
     * @name 查询列表
     * @param {Object} query 查询参数，一般为this.searchData
     * @param {Object} pageInfo 页面参数，包括pageSize和pageNo
     * @description 调用成功则刷新listData
     */
    getList(query, pageInfo) {
      if (!query.userName) {
        query.userName = this.userName;
      }
      this.listLoading = true;
      const queryParam = {
        ...pageInfo,
        ...query
      };
      if (queryParam.date) {
        queryParam.tousuBeginTime = queryParam.date[0];
        queryParam.tousuEndTime = queryParam.date[1];
      }
      searchApi(queryParam)
        .then(res => {
          this.listData = res.data.list;
          delete res.data.list;
          Object.assign(this.pageInfo, res.data);
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
    async lookEdit(row) {
      console.log("row--------");
      console.log(row);
      this.editData = Object.assign({}, row);
      this.editDialog = true;
    },
    /**
     * @name 编辑表单
     * @param {Object} row 表单数据，新增时为空
     * @description 调用成功打开表单对话框
     */
    showEdit(row) {
      if (!row) {
        this.isDual = false;
        this.editData = getData(editRule());
      } else {
        this.isDual = true;
        this.editData = getData(chuliRule());
        this.editData.tsjyId = row.id;
      }
      this.$nextTick(() => {
        this.editDialog = true;
      });
    },
    /**
     * @name 更新数据
     * @param editData 编辑的数据体
     * @description 调用成功关闭对话框并且刷新表单
     */
    async update(editData) {
      if (!this.validation()) return;
      this.editLoading = true;
      if (this.isDual) {
        editData.jiejueUserName = this.queryName
          ? this.queryName
          : this.userName;
        let { data, code, msg } = await chuliApi(editData).finally(
          () => (this.editLoading = false)
        );
        if (code == 200) {
          this.$notified.success({
            message: "处理完成"
          });
          this.getList(this.searchData, this.pageInfo);
          this.editDialog = false;
        } else {
          this.$notified.error({
            message: msg
          });
        }
        return;
      } else {
        editData.tousuUserNmae = this.queryName
          ? this.queryName
          : this.userName;
        let params = Object.assign({}, editData);
        params.path = params.path.toString();
        let { data, code, msg } = await updateApi(params).finally(
          () => (this.editLoading = false)
        );
        if (code == 200) {
          this.$notified.success({
            message: "新增数据成功"
          });
          this.getList(this.searchData, this.pageInfo);
          this.editDialog = false;
        } else {
          this.$notified.error({
            message: msg
          });
        }
      }
    },
    /**
     * @name 表单验证
     * @description 如果有则在此处写入逻辑
     * @returns {Boolean} 表单验证结果
     */
    validation() {
      let satate = false;
      this.editFormInstance.validate((valid, fail) => {
        satate = valid;
      });
      return satate;
    },
    /**
     * @name 删除数据项
     * @description 成功后会刷新列表
     */
    remove(row) {
      this.listLoading = true;
      removeApi({
        ids: [row.id]
      })
        .then(() => {
          this.$notified.success({
            message: "删除成功"
          });
          this.getList(this.searchData, this.pageInfo);
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
    /**
     * @name 重置表单数据
     */
    reset() {
      this?.editFormInstance?.resetFields();
    }
  }
};
</script>

<style lang="scss" scoped>
#complaint-advice-list {
  position: relative;
  overflow: hidden;
}
</style>
